const Controller = require('egg').Controller

class ArticleController extends Controller {
  /* 前台 */
  // 根据作者找文章(author)
  async getArticlesByAuthor() {
    try {
      const { ctx } = this
      const { author } = ctx.request.body
      const articles = await ctx.model.Article.findAll({
        where: {
          author_id: author
        }
      })
      ctx.body = {
        code: '0',
        desc: '获取文章成功',
        articles: articles
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '获取文章失败',
        err: error
      }
    }
  }

  // 根据收藏夹找文章(collection)
  async getArticlesByCollection() {
    try {
      const { ctx } = this
      const { collection } = ctx.request.body
      const articles = await ctx.model.Article.findAll({
        where: {
          col_id: collection
        }
      })
      ctx.body = {
        code: '0',
        desc: '获取文章成功',
        articles: articles
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '获取文章失败',
        err: error
      }
    }
  }

  // 根据id找文章
  async getArticleById() {
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      const detail = await ctx.model.Article.findByPk(id)
      ctx.body = {
        code: '0',
        desc: '获取文章成功',
        detail: detail
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '获取文章失败',
        err: error
      }
    }
  }

  // 喜欢文章+1
  async likeArticle() {
    try {
      const { ctx } = this
      const { id, like } = ctx.request.body
      await ctx.model.Article.update({
        like
      }, {
        where: {
          id
        }
      })
      ctx.body = {
        code: '0',
        desc: '点赞成功~'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '点赞失败',
        err: error
      }
    }
  }

  // 文章浏览量+1
  async viewArticle() {
    try {
      const { ctx } = this
      const { id, view } = ctx.request.body
      await ctx.model.Article.update({
        view
      }, {
        where: {
          id
        }
      })
      ctx.body = {
        code: '0'
      }
    } catch(error) {
      ctx.body = {
        code: '-1'
      }
    }
  }
}

module.exports = ArticleController